package com.imooc.Interceptor;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.google.gson.Gson;
import com.imooc.base.BaseInfoProperties;
import com.imooc.pojo.Admin;
import com.imooc.pojo.Users;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 @author liansen
 @create 01-28-16:04
*/
public class JwtCurrentUserInterceptor extends BaseInfoProperties implements HandlerInterceptor {

    public static final ThreadLocal<Users> currentUser = new ThreadLocal<>();

    public static final ThreadLocal<Admin> adminUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String appUserJson = request.getHeader(APP_USER_JSON);
        String saasUserJson = request.getHeader(SAAS_USER_JSON);
        String adminUserJson = request.getHeader(ADMIN_USER_JSON);

        if(StringUtils.isNotBlank(appUserJson)){
            Users user = new Gson().fromJson(appUserJson, Users.class);
            currentUser.set(user);
        }

        if(StringUtils.isNotBlank(saasUserJson)){
            Users user = new Gson().fromJson(saasUserJson, Users.class);
            currentUser.set(user);
        }

        if(StringUtils.isNotBlank(adminUserJson)){
            Admin admin = new Gson().fromJson(adminUserJson, Admin.class);
            adminUser.set(admin);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        currentUser.remove();
        adminUser.remove();
    }
}